package com.teacher.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teacher.common.CommonResult;
import com.teacher.pojo.json.PermissionList;
import com.teacher.service.IRoleService;
import com.teacher.pojo.vo.role.RoleAddVo;
import com.teacher.pojo.vo.role.RoleUpdatePermissionVo;
import com.teacher.pojo.vo.role.RoleUpdateVo;
import com.teacher.pojo.entity.Role;
import com.teacher.mapper.RoleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author zfm
 * @since 2020-12-16
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    /**
     * 添加角色
     *
     * @param roleAddVo
     * @return
     */
    @Override
    public CommonResult addRole(RoleAddVo roleAddVo) {
        Role role = new Role();
        BeanUtils.copyProperties(roleAddVo, role);
        PermissionList permissionList = new PermissionList();
        permissionList.setPermissionList(new ArrayList<>());
        role.setPermission(JSONUtil.toJsonStr(permissionList));
        if (baseMapper.insert(role) == 1) {
            return CommonResult.success("添加成功");
        }
        return CommonResult.failed("添加失败");
    }

    /**
     * update role's info except permission
     *
     * @param roleUpdateVo
     * @return
     */
    @Override
    public CommonResult updateRole(RoleUpdateVo roleUpdateVo) {
        Role role = new Role();
        BeanUtils.copyProperties(roleUpdateVo, role);
        if (baseMapper.updateById(role) == 1) {
            return CommonResult.success("更新成功");
        }
        return CommonResult.failed("更新失败");
    }

    /**
     * update permission by role's id
     *
     * @param roleUpdatePermissionVo
     * @return
     */
    @Override
    public CommonResult updatePermissionByRoleId(RoleUpdatePermissionVo roleUpdatePermissionVo) {
        // judge role whether exist
        PermissionList permissionList = new PermissionList();
        permissionList.setPermissionList(roleUpdatePermissionVo.getPermissionIds());
        Role role = new Role();
        role.setId(roleUpdatePermissionVo.getRoleId());
        role.setPermission(JSONUtil.toJsonStr(permissionList));
        if (baseMapper.updateById(role) == 1) {
            return CommonResult.success("更新成功");
        }
        return CommonResult.failed("更新失败");
    }

}
